package Server.Socket;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class ServerThread extends Thread {
	
	ServerSocket serverSocket;
	
	public static final int PORT = 8765;
	
	
   // BroadCast broadcast;
	Thread thread;
	String ip;
	InetAddress myIPaddress = null;
	
	public ServerThread(){
		
		try{
			serverSocket = new ServerSocket(PORT);
		}catch(IOException e){
			e.printStackTrace();
		}
		
		try{
			myIPaddress = InetAddress.getLocalHost();
		}catch(UnknownHostException e1){
			e1.printStackTrace();
		}
		
		ip = String.valueOf(myIPaddress);
		Server.jTextArea1.append("服务器地址："+String.valueOf(serverSocket.getLocalPort())+"\n");
		thread = new Thread(this);
		thread.start();
	}
	
	public void run(){
		while(true){
			try
			{
				Socket socket = serverSocket.accept();
				ClientThread clientThread = new ClientThread(socket,this);
				clientThread.start();
			
			}catch(IOException e){
				System.out.print("连接失败"+e.toString());
				System.exit(2);	
			}
		}
	}
	
    public void finalize(){
    	try
    	{
    		serverSocket.close();
    	}catch(IOException e){
    		e.printStackTrace();
    	}
    	serverSocket = null;
    }
}
